import { getToken } from '@/utils/local'
import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '@/views/Login'
// import Register from '@/views/Register'
// import Detail from '@/views/Detail'
// import Layout from '@/views/Layout'

// 1. 挂载VueRouter
Vue.use(VueRouter)

// 2.创建路由表
const router = new VueRouter({
  routes: [
    {
      path: '/login',
      component: () => import('@/views/Login')
    },
    {
      path: '/register',
      component: () => import('@/views/Register')
    },
    {
      path: '/detail/:id',
      component: () => import('@/views/Detail')
    },
    {
      path: '/',
      component: () => import('@/views/Layout'),
      children: [
        { path: 'article', component: () => import('@/views/Article') },
        { path: 'like', component: () => import('@/views/Like') },
        { path: 'collect', component: () => import('@/views/Collect') },
        { path: 'user', component: () => import('@/views/User') }
      ]
    }
  ]
})

const writeList = ['/register', '/login']
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    // 放行
    next()
  } else {
    if (writeList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})

export default router
